#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void* fun(void*);

pthread_mutex_t lock;

int main(int argc,char** argv)
{
  int ret;
  ret = pthread_mutex_init(&lock,NULL);
  if(ret != 0)
  {
    fprintf(stderr,"pthread_mutex_init is fail\n");
    exit(-1);
  }

  srand(time(NULL));

  pthread_t tid;
  ret = pthread_create(&tid,NULL,fun,NULL);
  if(ret != 0)
  {
    fprintf(stderr,"pthread_create is fail\n");
    exit(-1);
  }

  while(1)
  {
    ret = pthread_mutex_lock(&lock);
    if(ret != 0)
    {
      fprintf(stderr,"pthread_mutex_lock is fail\n");
      exit(-1);
    }
    printf("HELLO ");
    sleep(rand()%2);
    printf("WORLD\n");
    sleep(rand()%2);
    
    ret = pthread_mutex_unlock(&lock);
    if(ret != 0)
    {
      fprintf(stderr,"pthread_mutex_unlock is fail\n");
      exit(-1);
    }
  }
  pthread_mutex_destroy(&lock);
  pthread_join(tid,NULL);
  pthread_exit((void*)0);
}

void* fun(void* num)
{
  srand(time(NULL));
  int ret;
  while(1)
  {
    ret = pthread_mutex_lock(&lock);
    if(ret != 0)
    {
      fprintf(stderr,"pthread_mutex_lock is fail\n");
      exit(-1);
    }
    printf("hello ");
    sleep(rand()%3);
    printf("word\n");
    sleep(rand()%3);
    ret = pthread_mutex_unlock(&lock);
    if(ret != 0)
    {
      fprintf(stderr,"pthread_mutex_unlock is fail\n");
      exit(-1);
    }
  }
  return NULL;
}
